package com.colin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.colin.mapper.UserMapper;
import com.colin.pojo.User;
import com.colin.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

/**
 * @author 刘昱江
 * 时间 2021/5/11
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public String login(User user) {

        byte[] bytePass = user.getPassword().getBytes();
        String md5Pass = DigestUtils.md5DigestAsHex(bytePass);
        user.setPassword(md5Pass);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        User userResult = userMapper.selectOne(queryWrapper);
        if (userResult == null){
            return null ;
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        return token;
    }

    @Override
    public PageResult getList(String query,Integer pageNum, Integer pageSize) {
        PageResult pageResult = new PageResult();
        List<User> list;
        long total = 0;
        if(StringUtils.hasText(query)){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", query);
            list = userMapper.selectList(queryWrapper);
        } else {Integer start = (pageNum - 1)* pageSize;
            Integer end = pageSize;
            list = userMapper.getList(start, end);

            total = userMapper.selectCount(null);

        }



        pageResult.setTotal(total).setRows(list).setPageSize(pageSize).setPageNum(pageNum).setQuery(query);
        return pageResult;
    }
}
